<template>
  <div class="three-editor-container">
    <div class="editor-section">
      <div class="toolbar">
        <label class="auto-run-label">
          <input type="checkbox" v-model="autoRun" />
          自动运行
        </label>
        <button class="run-btn" @click="runCode" :disabled="autoRun">运行</button>
      </div>
      <div class="editor-label">基础HTML</div>
      <codemirror v-model="baseHtml" :extensions="htmlExtensions" class="editor" />
      <div class="editor-label">importmap</div>
      <codemirror v-model="importMap" :extensions="jsonExtensions" class="editor" />
      <div class="editor-label">module脚本</div>
      <codemirror v-model="moduleCode" :extensions="jsExtensions" class="editor" />
    </div>
    <div class="preview-section">
      <iframe :srcdoc="displayedCode" class="preview-iframe"></iframe>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { Codemirror } from 'vue-codemirror';
import { javascript } from '@codemirror/lang-javascript';
import { html } from '@codemirror/lang-html';
import { json } from '@codemirror/lang-json';
import { oneDark } from '@codemirror/theme-one-dark';

const htmlExtensions = [html(), oneDark];
const jsExtensions = [javascript(), oneDark];
const jsonExtensions = [json(), oneDark];

const baseHtml = ref(`<!DOCTYPE html>
<html lang="en">
<head>
  <title>three.js demo</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<style>
    body {
        margin: 0;
        padding: 1px;
        box-sizing: border-box;
        background-color: #1f1f1f;
        display: flex;
        flex-direction: column;
        width: 100vw;
        height: 100vh;
        overflow: hidden;
    }
    #box {
        width: 100%;
        height: 100%;
    }
</style>
<body>
</body>
</html>`);

const importMap = ref(`{
  "imports": {
    "three": "https://threejs.org/build/three.module.js",
    "three/addons/": "https://threejs.org/examples/jsm/"
  }
}`);

const moduleCode = ref(`import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// ... 你的 three.js 代码 ...
let scene = new THREE.Scene();
scene.background = new THREE.Color('maroon');
let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
camera.position.set(0, 5, 10);
let renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
window.addEventListener('resize', () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight);
});
let controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.target.set(0, 5, 0);
let grid = new THREE.GridHelper();
scene.add(grid);
let clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
  controls.update();
  renderer.render(scene, camera);
});`);

const autoRun = ref(true);
const displayedCode = ref('');

function buildHtml() {
  // 插入 importmap
  const importMapTag = `<script type="importmap">\n${importMap.value}\n<\/script>`;
  // 插入 module
  const moduleTag = `<script type="module">\n${moduleCode.value}\n<\/script>`;
  // 将 importmap 插入到 <head>，module 插入到 <body> 末尾
  let html = baseHtml.value;
  html = html.replace('</head>', `${importMapTag}\n</head>`);
  html = html.replace('</body>', `${moduleTag}\n</body>`);
  return html;
}

function runCode() {
  displayedCode.value = buildHtml();
}

watch(
  [baseHtml, importMap, moduleCode, autoRun],
  ([h, m, c, auto]) => {
    if (auto) {
      displayedCode.value = buildHtml();
    }
  },
  { immediate: true }
);
</script>

<style scoped>
.editor-label {
  font-size: 14px;
  color: #fff;
  padding: 8px 0 2px 2px;
  background: #000;
}
.three-editor-container {
  display: flex;
  flex-direction: row;
  height: 100vh;
}
.toolbar {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 12px 24px;
  top: 0;
  z-index: 10;
  position: absolute;
  color: #fff;
  right: 0;
}
.auto-run-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 15px;
  user-select: none;
}
.run-btn {
  padding: 6px 18px;
  background: #42b983;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}
.run-btn:disabled {
  background: #b2dfc7;
  cursor: not-allowed;
}
.editor-section {
  flex: 1.1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  position: relative;
}
.editor {
  flex: 1;
  min-height: 120px;
  border-radius: 6px;
  font-size: 15px;
  box-shadow: 0 2px 8px 0 rgba(60, 60, 60, 0.03);
  margin-bottom: 8px;
}
.preview-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}
.preview-iframe {
  flex: 1;
  width: 100%;
  border: none;
  background: #fff;
}
</style>
